package com.vote.www.controller;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class DownFileController {

	private static final Logger log = LoggerFactory
			.getLogger(DownFileController.class);
	
	@RequestMapping("down")
	public void downFile(@RequestParam(required = true) String filename, HttpServletRequest request, HttpServletResponse response){
	    
		InputStream in =null;
		OutputStream out =null;
		
        try {
			//获得请求文件名  
		/*	String filename = request.getParameter("filename");  
			System.out.println(filename);  */
			  
			//设置文件MIME类型  
			response.setContentType( request.getSession().getServletContext().getMimeType(filename));  
			//设置Content-Disposition  
			response.setHeader("Content-Disposition", "attachment;filename="+filename);  
			//读取目标文件，通过response将目标文件写到客户端  
			//获取目标文件的绝对路径  
			String fullFileName = request.getSession().getServletContext().getRealPath("/" + filename);  
			//System.out.println(fullFileName);  
			//读取文件  
			 in=new FileInputStream(fullFileName);  
			out= response.getOutputStream();  
			  
			//写文件  
			int b;  
			while((b=in.read())!= -1)  
			{  
			    out.write(b);  
			}  
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			log.error("error",e);
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				in.close();  
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
				log.error("error",e);
			}
		}
	}
}
